/**
 * 少儿英语启蒙岛 - 核心逻辑
 * Pico English Island - Core Logic
 * 
 * 架构设计:
 * - 数据驱动: 所有内容从database.json加载
 * - 智能预加载: 提前加载下一个资源,保证流畅体验
 * - 单页应用: 屏幕切换无刷新
 */

// ============================================
// 全局状态管理
// ============================================
const AppState = {
    database: null,              // 数据库
    currentCategory: null,       // 当前大类
    currentLesson: null,         // 当前课程
    currentMode: 'categories',   // 当前模式: categories, island, learn, quiz
    learnProgress: 0,            // 学习进度
    quizProgress: 0,             // 测试进度
    quizLives: 3,                // 测试生命值
    quizCorrect: 0,              // 测试正确数
    quizTotal: 0,                // 测试总题数
    currentAudio: null,          // 当前播放的音频
    audioTimeout: null,          // 音频播放定时器
    skipAutoPlay: false,         // 跳过自动播放（滑动时使用）
    showNativeLanguage: true,    // 是否显示母语（中文/日语等）
    preloadedImages: new Map(),  // 预加载的图片缓存
    swipeCount: 0,               // 滑动次数（用于隐藏提示）
    swipeInitialized: false,     // 滑动手势是否已初始化
    userStats: {
        totalStars: 0,
        completedLessons: []
    }
};

// ============================================
// DOM 元素引用
// ============================================
const DOM = {
    // 加载屏幕
    loadingScreen: null,
    
    // 应用容器
    app: null,
    
    // 导航栏
    btnBack: null,
    headerTitle: null,
    statStars: null,
    
    // 大类选择界面
    categoriesScreen: null,
    categoriesGrid: null,
    
    // 岛屿地图（小分类）
    islandMap: null,
    lessonsGrid: null,
    btnBackToCategories: null,
    categoryTitle: null,
    categorySubtitle: null,
    
    // 学习模式
    learnMode: null,
    btnBackFromLearn: null,
    learnLessonName: null,
    btnToggleLanguageLearn: null,
    learnProgress: null,
    learnProgressText: null,
    wordCard: null,
    cardImage: null,
    cardWordEn: null,
    cardWordCn: null,
    btnPlayAudio: null,
    btnPrev: null,
    btnNext: null,
    learnComplete: null,
    btnStartQuiz: null,
    
    // 测试模式
    quizMode: null,
    btnBackFromQuiz: null,
    quizLessonName: null,
    btnToggleLanguageQuiz: null,
    quizProgress: null,
    quizProgressText: null,
    livesContainer: null,
    btnQuizAudio: null,
    quizWordDisplay: null,
    quizOptions: null,
    quizFeedback: null,
    quizResult: null,
    resultTitle: null,
    scoreAccuracy: null,
    scoreStars: null,
    btnRetry: null,
    btnBackToMap: null
};

// ============================================
// 初始化应用
// ============================================
async function initApp() {
    console.log('🚀 初始化应用...');
    
    // 获取DOM元素
    initDOM();
    
    // 加载数据库
    await loadDatabase();
    
    // 初始化用户数据
    initUserData();
    
    // 渲染大类选择界面
    renderCategories();
    
    // 绑定事件
    bindEvents();
    
    // 隐藏加载屏幕,显示应用
    setTimeout(() => {
        DOM.loadingScreen.classList.add('hidden');
        setTimeout(() => {
            DOM.app.classList.remove('hidden');
        }, 300);
    }, 1000);
    
    console.log('✅ 应用初始化完成!');
}

// 初始化DOM引用
function initDOM() {
    // 加载屏幕
    DOM.loadingScreen = document.getElementById('loading-screen');
    
    // 应用容器
    DOM.app = document.getElementById('app');
    
    // 导航栏
    DOM.btnBack = document.getElementById('btnBack');
    DOM.headerTitle = document.getElementById('headerTitle');
    DOM.statStars = document.getElementById('statStars');
    
    // 大类选择界面
    DOM.categoriesScreen = document.getElementById('categories-screen');
    DOM.categoriesGrid = document.getElementById('categoriesGrid');
    
    // 岛屿地图（小分类）
    DOM.islandMap = document.getElementById('island-map');
    DOM.lessonsGrid = document.getElementById('lessonsGrid');
    DOM.btnBackToCategories = document.getElementById('btnBackToCategories');
    DOM.categoryTitle = document.getElementById('categoryTitle');
    DOM.categorySubtitle = document.getElementById('categorySubtitle');
    
    // 学习模式
    DOM.learnMode = document.getElementById('learn-mode');
    DOM.btnBackFromLearn = document.getElementById('btnBackFromLearn');
    DOM.learnLessonName = document.getElementById('learnLessonName');
    DOM.btnToggleLanguageLearn = document.getElementById('btnToggleLanguageLearn');
    DOM.learnProgress = document.getElementById('learnProgress');
    DOM.learnProgressText = document.getElementById('learnProgressText');
    DOM.wordCard = document.getElementById('wordCard');
    DOM.cardImage = document.getElementById('cardImage');
    DOM.cardWordEn = document.getElementById('cardWordEn');
    DOM.cardWordCn = document.getElementById('cardWordCn');
    DOM.btnPlayAudio = document.getElementById('btnPlayAudio');
    DOM.btnPrev = document.getElementById('btnPrev');
    DOM.btnNext = document.getElementById('btnNext');
    DOM.learnComplete = document.getElementById('learnComplete');
    DOM.btnStartQuiz = document.getElementById('btnStartQuiz');
    
    // 测试模式
    DOM.quizMode = document.getElementById('quiz-mode');
    DOM.btnBackFromQuiz = document.getElementById('btnBackFromQuiz');
    DOM.quizLessonName = document.getElementById('quizLessonName');
    DOM.btnToggleLanguageQuiz = document.getElementById('btnToggleLanguageQuiz');
    DOM.quizProgress = document.getElementById('quizProgress');
    DOM.quizProgressText = document.getElementById('quizProgressText');
    DOM.livesContainer = document.getElementById('livesContainer');
    DOM.btnQuizAudio = document.getElementById('btnQuizAudio');
    DOM.quizWordDisplay = document.getElementById('quizWordDisplay');
    DOM.quizOptions = document.getElementById('quizOptions');
    DOM.quizFeedback = document.getElementById('quizFeedback');
    DOM.quizResult = document.getElementById('quizResult');
    DOM.resultTitle = document.getElementById('resultTitle');
    DOM.scoreTotalQuestions = document.getElementById('scoreTotalQuestions');
    DOM.scoreCorrect = document.getElementById('scoreCorrect');
    DOM.scoreWrong = document.getElementById('scoreWrong');
    DOM.scoreAccuracy = document.getElementById('scoreAccuracy');
    DOM.scoreStars = document.getElementById('scoreStars');
    DOM.btnRetry = document.getElementById('btnRetry');
    DOM.btnBackToMap = document.getElementById('btnBackToMap');
}

// 加载数据库
async function loadDatabase() {
    try {
        console.log('📂 加载数据库...');
        const response = await fetch('database.json');
        AppState.database = await response.json();
        console.log(`✅ 数据库加载完成: ${Object.keys(AppState.database.dictionary).length}个单词, ${AppState.database.lessons.length}个课程`);
    } catch (error) {
        console.error('❌ 数据库加载失败:', error);
        alert('加载失败,请刷新页面重试');
    }
}

// 初始化用户数据
function initUserData() {
    // 从localStorage加载用户数据
    const savedData = localStorage.getItem('picoEnglish_userData');
    if (savedData) {
        try {
            AppState.userStats = JSON.parse(savedData);
        } catch (error) {
            console.error('用户数据解析失败:', error);
        }
    }
    
    // 从localStorage加载母语显示设置
    const savedLanguageSetting = localStorage.getItem('picoEnglish_showNativeLanguage');
    if (savedLanguageSetting !== null) {
        AppState.showNativeLanguage = savedLanguageSetting === 'true';
    }
    
    updateStatsDisplay();
    updateLanguageToggleUI();
}

// 保存用户数据
function saveUserData() {
    localStorage.setItem('picoEnglish_userData', JSON.stringify(AppState.userStats));
    updateStatsDisplay();
}

// 切换母语显示
function toggleNativeLanguage() {
    AppState.showNativeLanguage = !AppState.showNativeLanguage;
    
    // 保存到localStorage
    localStorage.setItem('picoEnglish_showNativeLanguage', AppState.showNativeLanguage.toString());
    
    // 更新UI
    updateLanguageToggleUI();
    
    console.log('👁️ 母语显示:', AppState.showNativeLanguage ? '开启' : '关闭');
}

// 更新切换按钮UI
function updateLanguageToggleUI() {
    if (AppState.showNativeLanguage) {
        document.body.classList.remove('hide-native-language');
        DOM.btnToggleLanguageLearn?.classList.remove('hide-language');
        DOM.btnToggleLanguageQuiz?.classList.remove('hide-language');
    } else {
        document.body.classList.add('hide-native-language');
        DOM.btnToggleLanguageLearn?.classList.add('hide-language');
        DOM.btnToggleLanguageQuiz?.classList.add('hide-language');
    }
}

// 更新统计显示
function updateStatsDisplay() {
    DOM.statStars.textContent = AppState.userStats.totalStars;
}

// ============================================
// 大类选择功能
// ============================================
function renderCategories() {
    console.log('🎨 渲染大类界面');
    DOM.categoriesGrid.innerHTML = '';
    
    AppState.database.categories.forEach(category => {
        // 统计该大类下的小分类数量
        const lessonsInCategory = AppState.database.lessons.filter(
            lesson => lesson.category === category.id
        );
        const lessonCount = lessonsInCategory.length;
        
        // 统计该大类下已完成的小分类数量
        const completedCount = lessonsInCategory.filter(
            lesson => AppState.userStats.completedLessons.includes(lesson.id)
        ).length;
        
        const card = document.createElement('div');
        card.className = 'category-card';
        card.innerHTML = `
            <div class="category-icon">${category.icon}</div>
            <h3 class="category-name">${category.name.replace(/^.+? /, '')}</h3>
            <p class="category-description">${category.description}</p>
            <div class="category-stats">
                <span class="category-count">${lessonCount}个主题</span>
                ${completedCount > 0 ? `<span class="category-progress">已完成 ${completedCount}/${lessonCount}</span>` : ''}
            </div>
        `;
        
        card.addEventListener('click', () => selectCategory(category));
        DOM.categoriesGrid.appendChild(card);
    });
}

// 选择大类
function selectCategory(category) {
    console.log('📂 选择大类:', category.name);
    AppState.currentCategory = category;
    
    // 更新小分类界面标题
    DOM.categoryTitle.innerHTML = `${category.icon} ${category.name.replace(/^.+? /, '')}`;
    DOM.categorySubtitle.textContent = `${category.description} - 选择一个主题开始学习`;
    
    // 渲染该大类下的小分类
    renderIslandMap();
    
    // 切换到小分类界面
    switchScreen('island');
}

// 返回大类选择
function backToCategories() {
    console.log('⬅️ 返回大类选择');
    AppState.currentCategory = null;
    switchScreen('categories');
}

// ============================================
// 小分类地图功能
// ============================================
function renderIslandMap() {
    DOM.lessonsGrid.innerHTML = '';
    
    // 如果选择了大类，只显示该大类下的课程
    const lessonsToShow = AppState.currentCategory
        ? AppState.database.lessons.filter(lesson => lesson.category === AppState.currentCategory.id)
        : AppState.database.lessons;
    
    lessonsToShow.forEach(lesson => {
        const isCompleted = AppState.userStats.completedLessons.includes(lesson.id);
        
        const card = document.createElement('div');
        card.className = `lesson-card ${isCompleted ? 'completed' : ''}`;
        card.innerHTML = `
            <div class="lesson-header">
                <div class="lesson-icon">${lesson.icon}</div>
                <div class="lesson-info">
                    <h3 class="lesson-name">${lesson.name}</h3>
                    <p class="lesson-count">${lesson.word_keys.length}个单词</p>
                </div>
            </div>
            ${isCompleted ? '<div class="lesson-status">✅</div>' : ''}
        `;
        
        card.addEventListener('click', () => startLesson(lesson));
        DOM.lessonsGrid.appendChild(card);
    });
}

// 开始课程 - 显示模式选择
function startLesson(lesson) {
    console.log('📚 选择课程:', lesson.name);
    AppState.currentLesson = lesson;
    
    // 显示模式选择对话框
    showModeSelection();
}

// 显示模式选择
function showModeSelection() {
    const modal = document.createElement('div');
    modal.className = 'mode-selection-modal';
    modal.innerHTML = `
        <div class="mode-selection-content">
            <h2 class="mode-selection-title">${AppState.currentLesson.icon} ${AppState.currentLesson.name}</h2>
            <p class="mode-selection-subtitle">请选择学习模式</p>
            <div class="mode-selection-buttons">
                <button class="mode-btn mode-btn-learn" id="btnSelectLearn">
                    <div class="mode-btn-icon">📚</div>
                    <div class="mode-btn-text">学习模式</div>
                    <div class="mode-btn-desc">查看单词和发音</div>
                </button>
                <button class="mode-btn mode-btn-quiz" id="btnSelectQuiz">
                    <div class="mode-btn-icon">📝</div>
                    <div class="mode-btn-text">测试模式</div>
                    <div class="mode-btn-desc">听音识图测试</div>
                </button>
            </div>
            <button class="mode-btn-close" id="btnCloseModal">✕</button>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 绑定事件
    document.getElementById('btnSelectLearn').addEventListener('click', () => {
        document.body.removeChild(modal);
        startLearnMode();
    });
    
    document.getElementById('btnSelectQuiz').addEventListener('click', () => {
        document.body.removeChild(modal);
        startQuiz();
    });
    
    document.getElementById('btnCloseModal').addEventListener('click', () => {
        document.body.removeChild(modal);
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    });
}

// 开始学习模式
function startLearnMode() {
    AppState.learnProgress = 0;
    AppState.swipeCount = 0; // 重置滑动计数
    switchScreen('learn');
    renderLearnMode();
    
    // 只初始化一次滑动手势
    if (!AppState.swipeInitialized) {
        initSwipeGesture();
        AppState.swipeInitialized = true;
    }
}

// ============================================
// 学习模式功能
// ============================================
function renderLearnMode() {
    const lesson = AppState.currentLesson;
    const words = lesson.word_keys;
    const currentIndex = AppState.learnProgress;
    
    console.log('📋 renderLearnMode - 当前索引:', currentIndex, '总单词数:', words.length, '当前单词:', words[currentIndex]);
    
    // 取消之前的音频定时器（防止重叠）
    if (AppState.audioTimeout) {
        console.log('❌ 取消之前的音频定时器');
        clearTimeout(AppState.audioTimeout);
        AppState.audioTimeout = null;
    }
    
    // 停止当前播放的音频
    if (AppState.currentAudio) {
        console.log('⏹️ 停止当前音频');
        AppState.currentAudio.pause();
        AppState.currentAudio.currentTime = 0;
        AppState.currentAudio = null;
    }
    
    // 更新进度条
    updateLearnProgress();
    
    // 显示当前单词
    if (currentIndex < words.length) {
        const wordKey = words[currentIndex];
        const wordData = AppState.database.dictionary[wordKey];
        
        // 重置卡片状态（在内容更新前）
        DOM.wordCard.style.transition = 'none';
        DOM.wordCard.style.transform = 'translateX(0) rotate(0deg)';
        DOM.wordCard.style.opacity = '1';
        
        // 更新内容
        showWord(wordData);
        
        // 预加载下一个单词的图片
        if (currentIndex + 1 < words.length) {
            preloadNextWord(words[currentIndex + 1]);
        }
        
        // 隐藏完成提示
        DOM.learnComplete.style.display = 'none';
        DOM.wordCard.style.display = 'block';
        DOM.btnPrev.style.display = 'flex';
        DOM.btnNext.style.display = 'flex';
        
        // 根据当前位置启用/禁用按钮
        if (currentIndex === 0) {
            DOM.btnPrev.disabled = true;
            console.log('🚫 上一个按钮已禁用（第一个单词）');
        } else {
            DOM.btnPrev.disabled = false;
            console.log('✅ 上一个按钮已启用');
        }
        
        if (currentIndex >= words.length - 1) {
            DOM.btnNext.disabled = true;
            console.log('🚫 下一个按钮已禁用（最后一个单词）');
        } else {
            DOM.btnNext.disabled = false;
            console.log('✅ 下一个按钮已启用，可以从', currentIndex, '到', currentIndex + 1);
        }
    } else {
        // 学习完成
        showLearnComplete();
    }
}

// 显示单词
function showWord(wordData) {
    console.log('🎯 显示单词:', wordData.word_en, 'skipAutoPlay:', AppState.skipAutoPlay);
    
    // 更新图片
    DOM.cardImage.src = wordData.image;
    DOM.cardImage.alt = wordData.word_cn;
    
    // 更新文字
    DOM.cardWordEn.textContent = wordData.word_en;
    DOM.cardWordCn.textContent = wordData.word_cn;
    
    // 短暂延迟后恢复过渡效果
    setTimeout(() => {
        DOM.wordCard.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
    }, 50);
    
    // 自动播放音频（除非skipAutoPlay被设置）
    if (!AppState.skipAutoPlay) {
        console.log('⏰ 设置音频定时器: 100ms后播放');
        AppState.audioTimeout = setTimeout(() => {
            console.log('🔊 自动播放音频:', wordData.word_en);
            playAudio(wordData.audio);
            AppState.audioTimeout = null; // 清理
        }, 100);
    } else {
        console.log('⏭️ 跳过自动播放（由滑动控制）');
        AppState.skipAutoPlay = false; // 重置标志
    }
}

// 预加载下一个单词
function preloadNextWord(wordKey) {
    const wordData = AppState.database.dictionary[wordKey];
    if (!wordData) return;
    
    // 预加载图片
    if (!AppState.preloadedImages.has(wordKey)) {
        const img = new Image();
        img.src = wordData.image;
        AppState.preloadedImages.set(wordKey, img);
    }
    
    // 预加载音频
    const audio = new Audio(wordData.audio);
    audio.preload = 'auto';
}

// 更新学习进度
function updateLearnProgress() {
    const total = AppState.currentLesson.word_keys.length;
    const current = AppState.learnProgress + 1; // 从1开始显示，而不是从0
    const percentage = (current / total) * 100;
    
    DOM.learnProgress.style.width = percentage + '%';
    DOM.learnProgressText.textContent = `${current}/${total}`;
}

// 上一个单词
function prevWord() {
    if (AppState.learnProgress > 0) {
        AppState.learnProgress--;
        renderLearnMode();
    }
}

// 下一个单词
function nextWord() {
    const totalWords = AppState.currentLesson.word_keys.length;
    console.log('➡️ nextWord 被调用，当前:', AppState.learnProgress, '总数:', totalWords);
    
    // 边界检查
    if (AppState.learnProgress < totalWords - 1) {
        AppState.learnProgress++;
        console.log('✅ 进度增加到:', AppState.learnProgress);
        renderLearnMode();
    } else {
        console.log('⚠️ 已经是最后一个单词，无法继续');
    }
}

// 初始化滑动手势
function initSwipeGesture() {
    let touchStartX = 0;
    let touchStartY = 0;
    let touchEndX = 0;
    let touchEndY = 0;
    let isDragging = false;
    
    const wordCard = DOM.wordCard;
    
    // 触摸开始
    wordCard.addEventListener('touchstart', (e) => {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
        isDragging = true;
        wordCard.style.transition = 'none'; // 移除过渡效果，使拖动更流畅
    }, { passive: true });
    
    // 触摸移动
    wordCard.addEventListener('touchmove', (e) => {
        if (!isDragging) return;
        
        const currentX = e.touches[0].clientX;
        const currentY = e.touches[0].clientY;
        const deltaX = currentX - touchStartX;
        const deltaY = currentY - touchStartY;
        
        // 只有水平滑动距离大于垂直滑动时才移动卡片
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            e.preventDefault(); // 防止页面滚动
            
            // 卡片跟随手指移动，添加阻尼效果
            const dampedDelta = deltaX * 0.5; // 0.5 是阻尼系数
            wordCard.style.transform = `translateX(${dampedDelta}px) rotate(${dampedDelta * 0.05}deg)`;
            
            // 根据滑动方向改变透明度
            const opacity = 1 - Math.abs(deltaX) / 500;
            wordCard.style.opacity = Math.max(0.5, opacity);
        }
    }, { passive: false });
    
    // 触摸结束
    wordCard.addEventListener('touchend', (e) => {
        if (!isDragging) return;
        
        touchEndX = e.changedTouches[0].clientX;
        touchEndY = e.changedTouches[0].clientY;
        
        const deltaX = touchEndX - touchStartX;
        const deltaY = touchEndY - touchStartY;
        
        // 恢复过渡效果
        wordCard.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
        
        // 判断滑动方向和距离
        if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 80) {
            if (deltaX > 0) {
                // 向右滑动 - 下一个单词
                if (AppState.learnProgress < AppState.currentLesson.word_keys.length - 1) {
                    console.log('👉 向右滑动，准备下一个单词');
                    animateCardOut('right');
                    // 等待动画完成后再更新内容和播放音频
                    setTimeout(() => {
                        console.log('⏱️ 动画完成，更新单词');
                        // 设置标志，阻止showWord的自动播放
                        AppState.skipAutoPlay = true;
                        AppState.learnProgress++;
                        renderLearnMode();
                        
                        // 滑动后延迟播放音频，确保UI完全更新
                        setTimeout(() => {
                            const wordKey = AppState.currentLesson.word_keys[AppState.learnProgress];
                            const wordData = AppState.database.dictionary[wordKey];
                            if (wordData) {
                                console.log('🎵 滑动后播放音频:', wordData.word_en);
                                playAudio(wordData.audio);
                            }
                        }, 200); // 延迟200ms播放
                    }, 320);
                } else {
                    // 已经是最后一个，弹回
                    wordCard.style.transform = 'translateX(0) rotate(0deg)';
                    wordCard.style.opacity = '1';
                }
            } else {
                // 向左滑动 - 上一个单词
                if (AppState.learnProgress > 0) {
                    console.log('👈 向左滑动，准备上一个单词');
                    animateCardOut('left');
                    // 等待动画完成后再更新内容和播放音频
                    setTimeout(() => {
                        console.log('⏱️ 动画完成，更新单词');
                        // 设置标志，阻止showWord的自动播放
                        AppState.skipAutoPlay = true;
                        AppState.learnProgress--;
                        renderLearnMode();
                        
                        // 滑动后延迟播放音频，确保UI完全更新
                        setTimeout(() => {
                            const wordKey = AppState.currentLesson.word_keys[AppState.learnProgress];
                            const wordData = AppState.database.dictionary[wordKey];
                            if (wordData) {
                                console.log('🎵 滑动后播放音频:', wordData.word_en);
                                playAudio(wordData.audio);
                            }
                        }, 200); // 延迟200ms播放
                    }, 320);
                } else {
                    // 已经是第一个，弹回
                    wordCard.style.transform = 'translateX(0) rotate(0deg)';
                    wordCard.style.opacity = '1';
                }
            }
        } else {
            // 滑动距离不够，弹回原位
            wordCard.style.transform = 'translateX(0) rotate(0deg)';
            wordCard.style.opacity = '1';
        }
        
        isDragging = false;
    }, { passive: true });
    
    // 触摸取消
    wordCard.addEventListener('touchcancel', () => {
        wordCard.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
        wordCard.style.transform = 'translateX(0) rotate(0deg)';
        wordCard.style.opacity = '1';
        isDragging = false;
    }, { passive: true });
}

// 卡片滑出动画 - 不自动重置，由 renderLearnMode 重置
function animateCardOut(direction) {
    const wordCard = DOM.wordCard;
    const translateX = direction === 'right' ? '150%' : '-150%';
    const rotate = direction === 'right' ? '30deg' : '-30deg';
    
    wordCard.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
    wordCard.style.transform = `translateX(${translateX}) rotate(${rotate})`;
    wordCard.style.opacity = '0';
}

// 显示学习完成
function showLearnComplete() {
    DOM.wordCard.style.display = 'none';
    DOM.btnPrev.style.display = 'none';
    DOM.btnNext.style.display = 'none';
    DOM.learnComplete.style.display = 'block';
}

// ============================================
// 测试模式功能
// ============================================
function startQuiz() {
    console.log('📝 开始测试');
    AppState.quizProgress = 0;
    AppState.quizLives = 3;
    AppState.quizCorrect = 0;
    AppState.quizAttempts = 0; // 总尝试次数（包括答错的）
    AppState.quizTotal = AppState.currentLesson.word_keys.length; // 测试所有单词
    
    switchScreen('quiz');
    renderQuizMode();
}

// 渲染测试模式
function renderQuizMode() {
    const currentIndex = AppState.quizProgress;
    
    if (currentIndex < AppState.quizTotal) {
        // 更新进度
        updateQuizProgress();
        
        // 更新生命值显示
        updateLivesDisplay();
        
        // 生成题目
        generateQuizQuestion();
        
        // 隐藏结果界面
        DOM.quizResult.style.display = 'none';
    } else {
        // 测试结束（完成所有题目）
        showQuizResult();
    }
}

// 生成测试题目
function generateQuizQuestion() {
    const lesson = AppState.currentLesson;
    const words = lesson.word_keys;
    const currentIndex = AppState.quizProgress;
    
    // 按顺序获取当前题目的正确答案（而不是随机选择）
    const correctWordKey = words[currentIndex];
    const correctWord = AppState.database.dictionary[correctWordKey];
    
    console.log('📝 生成测试题目:', currentIndex + 1, '/', words.length, '单词:', correctWord.word_en);
    
    // 随机选择3个错误选项
    const wrongOptions = [];
    while (wrongOptions.length < 3) {
        const randomKey = words[Math.floor(Math.random() * words.length)];
        if (randomKey !== correctWordKey && !wrongOptions.includes(randomKey)) {
            wrongOptions.push(randomKey);
        }
    }
    
    // 组合所有选项并打乱
    const allOptions = [correctWordKey, ...wrongOptions];
    shuffleArray(allOptions);
    
    // 保存正确答案
    AppState.currentQuizAnswer = correctWordKey;
    
    // 显示英文单词
    DOM.quizWordDisplay.textContent = correctWord.word_en;
    
    // 播放音频
    playAudio(correctWord.audio);
    
    // 渲染选项
    renderQuizOptions(allOptions, correctWordKey);
}

// 渲染测试选项
function renderQuizOptions(options, correctKey) {
    DOM.quizOptions.innerHTML = '';
    
    options.forEach(wordKey => {
        const wordData = AppState.database.dictionary[wordKey];
        
        const option = document.createElement('div');
        option.className = 'quiz-option';
        option.dataset.wordKey = wordKey;
        option.innerHTML = `
            <div class="option-image-wrapper">
                <img class="option-image" src="${wordData.image}" alt="${wordData.word_cn}">
            </div>
            <div class="option-text">${wordData.word_cn}</div>
            <div class="option-result-icon"></div>
        `;
        
        option.addEventListener('click', () => handleQuizAnswer(wordKey, correctKey, option));
        DOM.quizOptions.appendChild(option);
    });
}

// 处理测试答案
function handleQuizAnswer(selectedKey, correctKey, optionElement) {
    const isCorrect = selectedKey === correctKey;
    
    // 增加尝试次数
    AppState.quizAttempts++;
    
    if (isCorrect) {
        // 禁用所有选项
        const allOptions = DOM.quizOptions.querySelectorAll('.quiz-option');
        allOptions.forEach(opt => opt.classList.add('disabled'));
        
        // 正确答案
        AppState.quizCorrect++;
        optionElement.classList.add('correct');
        optionElement.querySelector('.option-result-icon').textContent = '✅';
        
        playSuccessSound();
        
        // 检查是否是最后一题
        const isLastQuestion = (AppState.quizProgress + 1) >= AppState.quizTotal;
        
        if (isLastQuestion) {
            // 最后一题，显示完成提示
            showFeedback(true, '所有题目完成!');
            // 1.5秒后显示结果
            setTimeout(() => {
                showQuizResult();
            }, 1500);
        } else {
            // 不是最后一题，直接进入下一题
            showFeedback(true);
            setTimeout(() => {
                AppState.quizProgress++;
                renderQuizMode();
            }, 1000);
        }
    } else {
        // 错误答案 - 只显示错误，不显示正确答案，让用户重新选择
        AppState.quizLives--;
        optionElement.classList.add('wrong');
        optionElement.querySelector('.option-result-icon').textContent = '❌';
        
        showFeedback(false, '');
        playErrorSound();
        updateLivesDisplay();
        
        // 1秒后移除错误标记，让用户重新选择
        // 不管生命值是否用完，都继续答题
        setTimeout(() => {
            optionElement.classList.remove('wrong');
            optionElement.querySelector('.option-result-icon').textContent = '';
        }, 1000);
    }
}

// 显示反馈
function showFeedback(isCorrect, customMessage = '') {
    DOM.quizFeedback.className = `quiz-feedback ${isCorrect ? 'correct' : 'wrong'}`;
    
    let feedbackText;
    if (customMessage) {
        feedbackText = customMessage;
    } else {
        feedbackText = isCorrect ? '回答正确!' : '答错了,再试一次!';
    }
    
    DOM.quizFeedback.querySelector('.feedback-text').textContent = feedbackText;
    DOM.quizFeedback.querySelector('.feedback-icon').textContent = isCorrect ? '✅' : '❌';
    
    DOM.quizFeedback.classList.add('show');
    
    setTimeout(() => {
        DOM.quizFeedback.classList.remove('show');
    }, 1500);
}

// 更新测试进度
function updateQuizProgress() {
    const current = AppState.quizProgress + 1; // 从1开始显示，而不是从0
    const percentage = (current / AppState.quizTotal) * 100;
    DOM.quizProgress.style.width = percentage + '%';
    DOM.quizProgressText.textContent = `${current}/${AppState.quizTotal}`;
}

// 更新生命值显示
function updateLivesDisplay() {
    const hearts = DOM.livesContainer.querySelectorAll('.heart');
    hearts.forEach((heart, index) => {
        if (index < AppState.quizLives) {
            heart.classList.remove('empty', 'lost');
            heart.classList.add('filled');
        } else {
            heart.classList.remove('filled');
            heart.classList.add('empty');
            if (index === AppState.quizLives) {
                heart.classList.add('lost');
            }
        }
    });
}

// 显示测试结果
function showQuizResult() {
    // 只要完成所有题目就算通过
    const passed = AppState.quizProgress >= AppState.quizTotal;
    
    // 计算答错次数
    const wrongAttempts = AppState.quizAttempts - AppState.quizCorrect;
    
    // 使用总尝试次数计算真实正确率
    const accuracy = AppState.quizAttempts > 0 
        ? Math.round((AppState.quizCorrect / AppState.quizAttempts) * 100)
        : 0;
    
    // 计算星星数（基于真实正确率）
    let stars = 0;
    if (passed) {
        if (accuracy >= 90) stars = 3;
        else if (accuracy >= 70) stars = 2;
        else if (accuracy >= 50) stars = 1;
    }
    
    // 更新显示
    DOM.resultTitle.textContent = passed ? '测试完成!' : '继续努力!';
    DOM.scoreTotalQuestions.textContent = AppState.quizTotal;
    DOM.scoreCorrect.textContent = AppState.quizCorrect;
    DOM.scoreWrong.textContent = wrongAttempts;
    DOM.scoreAccuracy.textContent = accuracy + '%';
    DOM.scoreStars.textContent = stars > 0 ? '⭐'.repeat(stars) : '继续加油!';
    
    // 保存进度
    if (passed && !AppState.userStats.completedLessons.includes(AppState.currentLesson.id)) {
        AppState.userStats.completedLessons.push(AppState.currentLesson.id);
        AppState.userStats.totalStars += stars;
        saveUserData();
    }
    
    // 显示结果
    DOM.quizResult.style.display = 'flex';
}

// ============================================
// 音频播放
// ============================================
function playAudio(audioPath) {
    // 停止当前音频
    if (AppState.currentAudio) {
        AppState.currentAudio.pause();
        AppState.currentAudio.currentTime = 0;
        AppState.currentAudio = null;
    }
    
    // 播放新音频
    try {
        AppState.currentAudio = new Audio(audioPath);
        AppState.currentAudio.play().catch(error => {
            console.warn('音频播放失败:', error);
        });
    } catch (error) {
        console.warn('创建音频失败:', error);
    }
}

// 播放成功音效
function playSuccessSound() {
    // 使用Web Audio API生成简单的成功音效
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);
    
    oscillator.frequency.value = 800;
    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
    
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.3);
}

// 播放错误音效
function playErrorSound() {
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        // 更低沉的错误音效
        oscillator.type = 'sawtooth';
        oscillator.frequency.value = 150;
        gainNode.gain.setValueAtTime(0.4, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.3);
        
        console.log('🔔 播放错误音效');
    } catch (error) {
        console.warn('错误音效播放失败:', error);
    }
}

// ============================================
// 屏幕切换
// ============================================
function switchScreen(screenName) {
    console.log('🔄 切换到屏幕:', screenName);
    
    // 隐藏所有屏幕
    DOM.categoriesScreen.classList.add('hidden');
    DOM.islandMap.classList.add('hidden');
    DOM.learnMode.classList.add('hidden');
    DOM.quizMode.classList.add('hidden');
    
    // 显示目标屏幕
    switch (screenName) {
        case 'categories':
            DOM.categoriesScreen.classList.remove('hidden');
            DOM.btnBack.style.display = 'none';
            DOM.headerTitle.textContent = '少儿英语启蒙岛';
            AppState.currentMode = 'categories';
            break;
        case 'island':
            DOM.islandMap.classList.remove('hidden');
            DOM.btnBack.style.display = 'none';
            DOM.headerTitle.textContent = AppState.currentCategory 
                ? AppState.currentCategory.name.replace(/^.+? /, '')
                : '少儿英语启蒙岛';
            AppState.currentMode = 'island';
            break;
        case 'learn':
            DOM.learnMode.classList.remove('hidden');
            DOM.btnBack.style.display = 'block';
            DOM.headerTitle.textContent = AppState.currentLesson.name;
            DOM.learnLessonName.textContent = AppState.currentLesson.name;
            AppState.currentMode = 'learn';
            updateModeTabs('learn');
            break;
        case 'quiz':
            DOM.quizMode.classList.remove('hidden');
            DOM.btnBack.style.display = 'block';
            DOM.headerTitle.textContent = AppState.currentLesson.name + ' - 测试';
            DOM.quizLessonName.textContent = AppState.currentLesson.name;
            AppState.currentMode = 'quiz';
            updateModeTabs('quiz');
            break;
    }
    
    // 滚动到顶部
    window.scrollTo(0, 0);
}

// 模式切换
function switchMode(targetMode) {
    console.log('🔄 切换模式:', AppState.currentMode, '→', targetMode);
    
    if (targetMode === 'learn') {
        // 切换到学习模式
        startLearnMode();
    } else if (targetMode === 'quiz') {
        // 切换到测试模式
        startQuiz();
    }
}

// 更新模式tabs的active状态
function updateModeTabs(activeMode) {
    document.querySelectorAll('.mode-tab').forEach(tab => {
        const mode = tab.getAttribute('data-mode');
        if (mode === activeMode) {
            tab.classList.add('active');
        } else {
            tab.classList.remove('active');
        }
    });
}

// ============================================
// 事件绑定
// ============================================
function bindEvents() {
    // 返回按钮
    DOM.btnBack.addEventListener('click', handleBackButton);
    
    // 返回大类按钮
    DOM.btnBackToCategories.addEventListener('click', backToCategories);
    
    // 学习/测试模式的返回按钮
    DOM.btnBackFromLearn.addEventListener('click', () => {
        switchScreen('island');
    });
    
    DOM.btnBackFromQuiz.addEventListener('click', () => {
        switchScreen('island');
    });
    
    // 模式切换tabs
    document.querySelectorAll('.mode-tab').forEach(tab => {
        tab.addEventListener('click', () => {
            const targetMode = tab.getAttribute('data-mode');
            switchMode(targetMode);
        });
    });
    
    // 切换母语显示按钮
    DOM.btnToggleLanguageLearn.addEventListener('click', toggleNativeLanguage);
    DOM.btnToggleLanguageQuiz.addEventListener('click', toggleNativeLanguage);
    
    // 学习模式
    DOM.btnPlayAudio.addEventListener('click', () => {
        const currentIndex = AppState.learnProgress;
        const wordKey = AppState.currentLesson.word_keys[currentIndex];
        const wordData = AppState.database.dictionary[wordKey];
        playAudio(wordData.audio);
    });
    
    // 点击图片也能播放音频
    DOM.cardImage.addEventListener('click', () => {
        const currentIndex = AppState.learnProgress;
        const wordKey = AppState.currentLesson.word_keys[currentIndex];
        const wordData = AppState.database.dictionary[wordKey];
        playAudio(wordData.audio);
        
        // 添加点击反馈动画
        DOM.cardImage.style.transform = 'scale(0.95)';
        setTimeout(() => {
            DOM.cardImage.style.transform = 'scale(1)';
        }, 150);
    });
    
    DOM.btnPrev.addEventListener('click', prevWord);
    DOM.btnNext.addEventListener('click', nextWord);
    DOM.btnStartQuiz.addEventListener('click', startQuiz);
    
    // 测试模式
    DOM.btnQuizAudio.addEventListener('click', () => {
        const wordData = AppState.database.dictionary[AppState.currentQuizAnswer];
        if (wordData) {
            playAudio(wordData.audio);
            DOM.btnQuizAudio.classList.add('playing');
            setTimeout(() => {
                DOM.btnQuizAudio.classList.remove('playing');
            }, 500);
        }
    });
    
    DOM.btnRetry.addEventListener('click', startQuiz);
    DOM.btnBackToMap.addEventListener('click', () => {
        renderIslandMap(); // 重新渲染以显示新完成的课程
        switchScreen('island');
    });
    
    // 键盘快捷键
    document.addEventListener('keydown', handleKeyboard);
}

// 处理返回按钮
function handleBackButton() {
    if (AppState.currentMode === 'learn') {
        // 确认是否退出学习
        if (confirm('确定要退出当前学习吗?')) {
            switchScreen('island');
            renderIslandMap();
        }
    } else if (AppState.currentMode === 'quiz') {
        // 确认是否退出测试
        if (confirm('确定要退出当前测试吗?')) {
            switchScreen('island');
            renderIslandMap();
        }
    } else if (AppState.currentMode === 'island') {
        // 从小分类返回大类
        backToCategories();
    }
}

// 处理键盘事件
function handleKeyboard(event) {
    if (AppState.currentMode === 'learn') {
        if (event.key === 'ArrowRight' || event.key === ' ') {
            event.preventDefault();
            if (AppState.learnProgress < AppState.currentLesson.word_keys.length) {
                nextWord();
            }
        }
    }
}

// ============================================
// 工具函数
// ============================================

// 打乱数组
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// ============================================
// 应用启动
// ============================================
document.addEventListener('DOMContentLoaded', () => {
    console.log('🏝️ 欢迎来到少儿英语启蒙岛!');
    initApp();
});

// 处理页面可见性变化(暂停音频等)
document.addEventListener('visibilitychange', () => {
    if (document.hidden && AppState.currentAudio) {
        AppState.currentAudio.pause();
    }
});

// 防止意外关闭
window.addEventListener('beforeunload', (event) => {
    if (AppState.currentMode !== 'island') {
        event.preventDefault();
        event.returnValue = '';
    }
});

